//基于第一版的基础上修改了一下，使用开放API

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Harmony Player</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #2a4d69);
            color: #fff;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            width: 100%;
            max-width: 1200px;
            display: flex;
            background: rgba(25, 20, 40, 0.85);
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.5);
            height: 90vh;
        }
        
        /* 左侧导航栏样式 */
        .sidebar {
            width: 280px;
            background: rgba(15, 10, 30, 0.9);
            padding: 25px 15px;
            display: flex;
            flex-direction: column;
            border-right: 1px solid rgba(255, 255, 255, 0.1);
            overflow-y: auto;
        }
        
        .logo {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            color: #9b5de5;
        }
        
        .logo i {
            margin-right: 10px;
            font-size: 28px;
        }
        
        .nav-section {
            margin-bottom: 30px;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #7f8c8d;
            margin-bottom: 15px;
            padding-left: 10px;
        }
        
        .nav-item {
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .nav-item:hover {
            background: rgba(155, 93, 229, 0.2);
        }
        
        .nav-item.active {
            background: rgba(155, 93, 229, 0.4);
        }
        
        .nav-item i {
            margin-right: 12px;
            font-size: 18px;
            width: 24px;
            text-align: center;
        }
        
        .playlist-section {
            flex-grow: 1;
            overflow-y: auto;
        }
        
        .playlist-item {
            padding: 10px 15px;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .playlist-item:hover {
            background: rgba(155, 93, 229, 0.2);
        }
        
        .playlist-name {
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 160px;
        }
        
        .song-count {
            color: #7f8c8d;
            font-size: 13px;
        }
        
        /* 主内容区样式 */
        .main-content {
            flex: 1;
            padding: 30px;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            gap: 15px;
        }
        
        .search-box {
            display: flex;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 30px;
            padding: 8px 15px;
            flex: 1;
            max-width: 500px;
        }
        
        .search-box input {
            background: transparent;
            border: none;
            color: white;
            outline: none;
            flex: 1;
            padding: 5px 10px;
        }
        
        .search-box button {
            background: transparent;
            border: none;
            color: #9b5de5;
            cursor: pointer;
        }
        
        .import-btn {
            background: linear-gradient(90deg, #9b5de5, #f15bb5);
            border: none;
            border-radius: 30px;
            color: white;
            padding: 12px 25px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            transition: all 0.3s ease;
            white-space: nowrap;
        }
        
        .import-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(155, 93, 229, 0.4);
        }
        
        .import-btn i {
            margin-right: 8px;
        }
        
        /* 播放器样式 */
        .player-container {
            background: rgba(30, 25, 50, 0.7);
            border-radius: 20px;
            padding: 30px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        
        .now-playing {
            display: flex;
            margin-bottom: 40px;
            gap: 30px;
        }
        
        .album-art {
            width: 220px;
            height: 220px;
            border-radius: 15px;
            background: linear-gradient(45deg, #9b5de5, #00bbf9);
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            flex-shrink: 0;
        }
        
        .album-art img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .album-art i {
            font-size: 80px;
            color: rgba(255, 255, 255, 0.7);
        }
        
        .song-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            min-width: 0;
        }
        
        .song-title {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .song-artist {
            font-size: 20px;
            color: #9b5de5;
            margin-bottom: 20px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .song-album {
            font-size: 16px;
            color: #7f8c8d;
            margin-bottom: 30px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .controls {
            display: flex;
            align-items: center;
        }
        
        .control-btn {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            border: none;
            color: white;
            font-size: 18px;
            margin: 0 10px;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .control-btn:hover {
            background: rgba(155, 93, 229, 0.5);
            transform: scale(1.1);
        }
        
        .play-btn {
            width: 70px;
            height: 70px;
            background: linear-gradient(90deg, #9b5de5, #f15bb5);
            font-size: 24px;
        }
        
        /* 进度条 */
        .progress-container {
            margin: 30px 0;
        }
        
        .progress-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 14px;
            color: #bdc3c7;
        }
        
        .progress-bar {
            height: 6px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
            overflow: hidden;
            cursor: pointer;
        }
        
        .progress {
            height: 100%;
            background: linear-gradient(90deg, #9b5de5, #f15bb5);
            width: 30%;
            border-radius: 3px;
            position: relative;
        }
        
        .progress::after {
            content: '';
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 12px;
            height: 12px;
            background: white;
            border-radius: 50%;
            opacity: 0;
            transition: opacity 0.2s;
        }
        
        .progress-bar:hover .progress::after {
            opacity: 1;
        }
        
        /* 播放列表 */
        .playlist-title {
            font-size: 22px;
            font-weight: 600;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }
        
        .playlist-title i {
            margin-right: 10px;
            color: #9b5de5;
        }
        
        .song-list {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .song-item {
            display: flex;
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .song-item:hover {
            background: rgba(155, 93, 229, 0.2);
        }
        
        .song-item.playing {
            background: rgba(155, 93, 229, 0.3);
        }
        
        .song-number {
            width: 30px;
            color: #7f8c8d;
            display: flex;
            align-items: center;
        }
        
        .song-details {
            flex: 1;
            min-width: 0;
        }
        
        .song-item-title {
            font-weight: 500;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .song-item-artist {
            font-size: 13px;
            color: #7f8c8d;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .song-duration {
            color: #7f8c8d;
            display: flex;
            align-items: center;
            padding-left: 10px;
        }
        
        /* 搜索区域 */
        .search-results {
            margin-top: 20px;
            background: rgba(30, 25, 50, 0.7);
            border-radius: 15px;
            padding: 20px;
        }
        
        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .results-title {
            font-size: 18px;
            font-weight: 600;
        }
        
        .result-item {
            display: flex;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .result-item:hover {
            background: rgba(155, 93, 229, 0.2);
        }
        
        .result-art {
            width: 50px;
            height: 50px;
            border-radius: 8px;
            background: linear-gradient(45deg, #9b5de5, #00bbf9);
            margin-right: 15px;
            flex-shrink: 0;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .result-art img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .result-art i {
            color: rgba(255, 255, 255, 0.7);
        }
        
        .result-details {
            flex: 1;
            min-width: 0;
        }
        
        .result-title {
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .result-artist {
            font-size: 13px;
            color: #7f8c8d;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        /* 响应式设计 */
        @media (max-width: 900px) {
            .container {
                flex-direction: column;
                height: auto;
            }
            
            .sidebar {
                width: 100%;
                border-right: none;
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            }
            
            .now-playing {
                flex-direction: column;
                align-items: center;
                text-align: center;
            }
            
            .album-art {
                margin-bottom: 25px;
            }
            
            .controls {
                justify-content: center;
            }
        }
        
        @media (max-width: 600px) {
            .header {
                flex-direction: column;
                gap: 15px;
            }
            
            .search-box, .import-btn {
                width: 100%;
                max-width: none;
            }
            
            .player-container {
                padding: 20px;
            }
            
            .now-playing {
                gap: 20px;
            }
            
            .album-art {
                width: 180px;
                height: 180px;
            }
            
            .song-title {
                font-size: 26px;
            }
            
            .song-artist {
                font-size: 18px;
            }
        }
        
        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: rgba(155, 93, 229, 0.5);
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: rgba(155, 93, 229, 0.8);
        }
        
        /* 加载动画 */
        .loader {
            text-align: center;
            padding: 20px;
            color: #9b5de5;
        }
        
        .loader i {
            font-size: 24px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 30px;
            color: #7f8c8d;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            color: #9b5de5;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            background: rgba(155, 93, 229, 0.9);
            border-radius: 10px;
            color: white;
            font-weight: 500;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            transform: translateX(120%);
            transition: transform 0.3s ease;
            z-index: 1000;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .api-status {
            padding: 10px;
            background: rgba(30, 25, 50, 0.7);
            border-radius: 8px;
            margin-top: 15px;
            font-size: 14px;
        }
        
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-online {
            background: #2ecc71;
        }
        
        .status-offline {
            background: #e74c3c;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧导航栏 -->
        <div class="sidebar">
            <div class="logo">
                <i class="fas fa-music"></i>
                <span>Harmony Player</span>
            </div>
            
            <div class="nav-section">
                <div class="section-title">发现音乐</div>
                <div class="nav-item active" data-section="search">
                    <i class="fas fa-search"></i>
                    <span>搜索</span>
                </div>
                <div class="nav-item" data-section="recommend">
                    <i class="fas fa-fire"></i>
                    <span>推荐歌单</span>
                </div>
                <div class="nav-item" data-section="charts">
                    <i class="fas fa-chart-line"></i>
                    <span>排行榜</span>
                </div>
            </div>
            
            <div class="nav-section">
                <div class="section-title">我的音乐</div>
                <div class="nav-item" data-section="history">
                    <i class="fas fa-history"></i>
                    <span>播放历史</span>
                </div>
                <div class="nav-item" data-section="local">
                    <i class="fas fa-folder"></i>
                    <span>本地音乐</span>
                </div>
                <div class="nav-item" data-section="favorites">
                    <i class="fas fa-heart"></i>
                    <span>我的收藏</span>
                </div>
            </div>
            
            <div class="playlist-section">
                <div class="section-title">我的歌单</div>
                <div class="playlist-item active" data-playlist="default">
                    <span class="playlist-name">默认歌单</span>
                    <span class="song-count">0首</span>
                </div>
                <div class="playlist-item" data-playlist="favorites">
                    <span class="playlist-name">收藏夹</span>
                    <span class="song-count">0首</span>
                </div>
                <div class="playlist-item" data-playlist="recent">
                    <span class="playlist-name">最近播放</span>
                    <span class="song-count">0首</span>
                </div>
            </div>
            
            <div class="api-status">
                <div>
                    <span class="status-indicator status-online"></span>
                    <span>Audius API: 在线</span>
                </div>
                <div style="margin-top: 8px; font-size: 12px;">
                    使用开放音乐API提供音乐服务
                </div>
            </div>
        </div>
        
        <!-- 主内容区 -->
        <div class="main-content">
            <div class="header">
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索音乐、歌单、歌手...">
                    <button id="searchBtn"><i class="fas fa-search"></i></button>
                </div>
                <button class="import-btn" id="importBtn">
                    <i class="fas fa-plus"></i>
                    导入本地音乐
                </button>
            </div>
            
            <div class="player-container">
                <div class="now-playing">
                    <div class="album-art">
                        <i class="fas fa-music" id="defaultArtIcon"></i>
                        <img id="albumArt" src="" alt="Album Art" style="display: none;">
                    </div>
                    <div class="song-info">
                        <h1 class="song-title" id="songTitle">Harmony Player</h1>
                        <div class="song-artist" id="songArtist">准备好享受音乐</div>
                        <div class="song-album" id="songAlbum">选择歌曲开始播放</div>
                        
                        <div class="controls">
                            <button class="control-btn" id="prevBtn">
                                <i class="fas fa-step-backward"></i>
                            </button>
                            <button class="control-btn play-btn" id="playBtn">
                                <i class="fas fa-play"></i>
                            </button>
                            <button class="control-btn" id="nextBtn">
                                <i class="fas fa-step-forward"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="progress-container">
                    <div class="progress-info">
                        <span id="currentTime">0:00</span>
                        <span id="totalTime">0:00</span>
                    </div>
                    <div class="progress-bar" id="progressBarContainer">
                        <div class="progress" id="progressBar"></div>
                    </div>
                </div>
                
                <div class="volume-container">
                    <div class="progress-info">
                        <span>音量</span>
                        <span id="volumePercent">70%</span>
                    </div>
                    <div class="progress-bar" id="volumeBarContainer">
                        <div class="progress" id="volumeBar" style="width: 70%;"></div>
                    </div>
                </div>
                
                <h2 class="playlist-title">
                    <i class="fas fa-list"></i>
                    当前播放列表
                </h2>
                
                <div class="song-list" id="playlist">
                    <div class="empty-state" id="emptyPlaylist">
                        <i class="fas fa-music"></i>
                        <p>播放列表为空</p>
                        <p>请搜索音乐或导入本地音乐</p>
                    </div>
                </div>
                
                <!-- 搜索结果显示区域 -->
                <div class="search-results" id="searchResults" style="display: none;">
                    <div class="results-header">
                        <div class="results-title">搜索结果</div>
                        <div id="resultsCount">0 首歌曲</div>
                    </div>
                    <div class="results-container" id="resultsContainer">
                        <div class="empty-state" id="emptyResults">
                            <i class="fas fa-search"></i>
                            <p>输入关键词搜索音乐</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="notification" id="notification">歌曲已添加到播放列表</div>
    
    <input type="file" id="fileInput" accept="audio/*" multiple style="display: none;">
    
    <script>
        // 音乐播放器核心功能
        const audioPlayer = new Audio();
        let currentPlaylist = [];
        let currentSongIndex = -1;
        let isPlaying = false;
        
        // DOM元素
        const playBtn = document.getElementById('playBtn');
        const prevBtn = document.getElementById('prevBtn');
        const nextBtn = document.getElementById('nextBtn');
        const importBtn = document.getElementById('importBtn');
        const fileInput = document.getElementById('fileInput');
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        const playlist = document.getElementById('playlist');
        const searchResults = document.getElementById('searchResults');
        const resultsContainer = document.getElementById('resultsContainer');
        const emptyPlaylist = document.getElementById('emptyPlaylist');
        const notification = document.getElementById('notification');
        
        // Audius API端点
        const AUDIUS_API_ENDPOINTS = [
            "https://api.audius.co",
            "https://audius-api-1.cultur3stake.com",
            "https://audius-api-2.cultur3stake.com"
        ];
        
        // 初始化播放器
        function initPlayer() {
            // 播放控制
            playBtn.addEventListener('click', togglePlay);
            prevBtn.addEventListener('click', playPrev);
            nextBtn.addEventListener('click', playNext);
            
            // 导入音乐
            importBtn.addEventListener('click', () => fileInput.click());
            fileInput.addEventListener('change', handleFileSelect);
            
            // 搜索功能
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') searchMusic();
            });
            searchBtn.addEventListener('click', searchMusic);
            
            // 进度条控制
            document.getElementById('progressBarContainer').addEventListener('click', seekAudio);
            document.getElementById('volumeBarContainer').addEventListener('click', adjustVolume);
            
            // 播放器事件监听
            audioPlayer.addEventListener('timeupdate', updateProgress);
            audioPlayer.addEventListener('ended', playNext);
            audioPlayer.addEventListener('loadedmetadata', () => {
                document.getElementById('totalTime').textContent = formatTime(audioPlayer.duration);
            });
            
            // 初始音量设置
            audioPlayer.volume = 0.7;
            
            // 添加一些初始音乐
            addInitialTracks();
        }
        
        // 添加初始音乐
        async function addInitialTracks() {
            try {
                const tracks = await searchAudiusTracks("electronic", 3);
                tracks.forEach(track => {
                    addToPlaylist(track);
                });
            } catch (error) {
                console.error('获取初始音乐失败:', error);
                // 添加一些默认音乐
                const defaultTracks = [
                    {
                        id: "default1",
                        title: "Welcome to Harmony",
                        artist: "Harmony Player",
                        duration: 180,
                        cover: "https://source.unsplash.com/random/300x300/?music",
                        url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
                    },
                    {
                        id: "default2",
                        title: "Digital Dreams",
                        artist: "Neon Pulse",
                        duration: 225,
                        cover: "https://source.unsplash.com/random/300x300/?digital",
                        url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"
                    }
                ];
                
                defaultTracks.forEach(track => {
                    addToPlaylist(track);
                });
            }
        }
        
        // 播放/暂停切换
        function togglePlay() {
            if (currentPlaylist.length === 0) {
                showNotification("播放列表为空，请添加歌曲");
                return;
            }
            
            if (isPlaying) {
                audioPlayer.pause();
                playBtn.querySelector('i').className = 'fas fa-play';
            } else {
                if (currentSongIndex === -1) {
                    currentSongIndex = 0;
                    loadSong(currentSongIndex);
                }
                audioPlayer.play()
                    .then(() => {
                        playBtn.querySelector('i').className = 'fas fa-pause';
                        isPlaying = true;
                    })
                    .catch(error => {
                        showNotification("播放失败: " + error.message);
                        console.error('播放失败:', error);
                    });
            }
        }
        
        // 播放上一首
        function playPrev() {
            if (currentPlaylist.length === 0) return;
            
            currentSongIndex--;
            if (currentSongIndex < 0) {
                currentSongIndex = currentPlaylist.length - 1;
            }
            loadSong(currentSongIndex);
            if (isPlaying) audioPlayer.play();
        }
        
        // 播放下一首
        function playNext() {
            if (currentPlaylist.length === 0) return;
            
            currentSongIndex++;
            if (currentSongIndex >= currentPlaylist.length) {
                currentSongIndex = 0;
            }
            loadSong(currentSongIndex);
            if (isPlaying) audioPlayer.play();
        }
        
        // 加载歌曲
        function loadSong(index) {
            const song = currentPlaylist[index];
            
            // 检查URL是否有效
            if (!song.url) {
                showNotification("无效的音频URL");
                return;
            }
            
            audioPlayer.src = song.url;
            audioPlayer.load();
            
            // 更新UI
            document.getElementById('songTitle').textContent = song.title;
            document.getElementById('songArtist').textContent = song.artist || '未知艺术家';
            document.getElementById('songAlbum').textContent = song.album || '未知专辑';
            
            // 更新播放列表高亮
            document.querySelectorAll('.song-item').forEach(item => {
                item.classList.remove('playing');
            });
            document.querySelectorAll('.song-item')[index].classList.add('playing');
            
            // 更新专辑封面
            const albumArt = document.getElementById('albumArt');
            const defaultIcon = document.getElementById('defaultArtIcon');
            if (song.cover) {
                albumArt.src = song.cover;
                albumArt.style.display = 'block';
                defaultIcon.style.display = 'none';
            } else {
                albumArt.style.display = 'none';
                defaultIcon.style.display = 'block';
            }
            
            // 设置当前时间
            document.getElementById('currentTime').textContent = formatTime(0);
            document.getElementById('totalTime').textContent = formatTime(song.duration);
            document.getElementById('progressBar').style.width = '0%';
        }
        
        // 更新进度条
        function updateProgress() {
            if (audioPlayer.duration) {
                const percent = (audioPlayer.currentTime / audioPlayer.duration) * 100;
                document.getElementById('progressBar').style.width = `${percent}%`;
                document.getElementById('currentTime').textContent = formatTime(audioPlayer.currentTime);
            }
        }
        
        // 进度条跳转
        function seekAudio(e) {
            const progressBar = e.currentTarget;
            const clickPosition = e.clientX - progressBar.getBoundingClientRect().left;
            const progressWidth = progressBar.clientWidth;
            const percent = (clickPosition / progressWidth);
            
            audioPlayer.currentTime = percent * audioPlayer.duration;
        }
        
        // 调整音量
        function adjustVolume(e) {
            const volumeBar = e.currentTarget;
            const clickPosition = e.clientX - volumeBar.getBoundingClientRect().left;
            const progressWidth = volumeBar.clientWidth;
            const percent = Math.min(1, Math.max(0, clickPosition / progressWidth));
            
            document.getElementById('volumeBar').style.width = `${percent * 100}%`;
            document.getElementById('volumePercent').textContent = `${Math.round(percent * 100)}%`;
            audioPlayer.volume = percent;
        }
        
        // 处理文件选择
        function handleFileSelect(e) {
            const files = e.target.files;
            if (files.length === 0) return;
            
            // 清空文件输入，允许再次选择相同文件
            fileInput.value = '';
            
            let addedCount = 0;
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (!file.type.startsWith('audio/')) continue;
                
                const url = URL.createObjectURL(file);
                
                // 创建歌曲对象
                const song = {
                    id: Date.now() + i,
                    title: file.name.replace(/\.[^/.]+$/, ""), // 移除扩展名
                    artist: "本地音乐",
                    album: "本地文件",
                    duration: "0:00",
                    url: url,
                    cover: "https://source.unsplash.com/random/300x300/?music,note",
                    isLocal: true
                };
                
                // 添加到播放列表
                addToPlaylist(song);
                addedCount++;
            }
            
            if (addedCount > 0) {
                showNotification(`成功导入 ${addedCount} 首音乐`);
                
                // 更新歌单计数
                updatePlaylistCount();
            }
        }
        
        // 添加歌曲到播放列表
        function addToPlaylist(song) {
            currentPlaylist.push(song);
            
            // 隐藏空状态
            emptyPlaylist.style.display = 'none';
            
            // 创建播放列表项
            const songItem = document.createElement('div');
            songItem.className = 'song-item';
            songItem.innerHTML = `
                <div class="song-number">${currentPlaylist.length}</div>
                <div class="song-details">
                    <div class="song-item-title">${song.title}</div>
                    <div class="song-item-artist">${song.artist}</div>
                </div>
                <div class="song-duration">${formatTime(song.duration)}</div>
            `;
            
            // 点击播放
            songItem.addEventListener('click', () => {
                currentSongIndex = Array.from(playlist.children).indexOf(songItem);
                loadSong(currentSongIndex);
                if (!isPlaying) {
                    isPlaying = true;
                    audioPlayer.play()
                        .then(() => {
                            playBtn.querySelector('i').className = 'fas fa-pause';
                        })
                        .catch(error => {
                            showNotification("播放失败: " + error.message);
                        });
                }
            });
            
            playlist.appendChild(songItem);
        }
        
        // 更新歌单计数
        function updatePlaylistCount() {
            const countElements = document.querySelectorAll('.song-count');
            countElements.forEach(el => {
                const playlistId = el.closest('.playlist-item').dataset.playlist;
                if (playlistId === 'default') {
                    el.textContent = `${currentPlaylist.length}首`;
                }
            });
        }
        
        // 格式化时间
        function formatTime(seconds) {
            if (isNaN(seconds)) return "0:00";
            
            const min = Math.floor(seconds / 60);
            const sec = Math.floor(seconds % 60);
            return `${min}:${sec < 10 ? '0' : ''}${sec}`;
        }
        
        // 搜索音乐
        async function searchMusic() {
            const query = searchInput.value.trim();
            if (!query) return;
            
            // 显示搜索区域
            searchResults.style.display = 'block';
            
            // 显示加载状态
            resultsContainer.innerHTML = '<div class="loader"><i class="fas fa-spinner"></i><p>搜索中...</p></div>';
            
            try {
                // 使用Audius API搜索音乐
                const results = await searchAudiusTracks(query, 20);
                
                // 显示结果
                displaySearchResults(results);
            } catch (error) {
                resultsContainer.innerHTML = '<div class="empty-state"><i class="fas fa-exclamation-circle"></i><p>搜索失败，请稍后再试</p></div>';
                console.error('搜索失败:', error);
            }
        }
        
        // 使用Audius API搜索音乐
        async function searchAudiusTracks(query, limit = 10) {
            // 尝试多个API端点
            for (const endpoint of AUDIUS_API_ENDPOINTS) {
                try {
                    const response = await fetch(`${endpoint}/v1/tracks/search?query=${encodeURIComponent(query)}&limit=${limit}`);
                    if (!response.ok) throw new Error(`API响应错误: ${response.status}`);
                    
                    const data = await response.json();
                    
                    // 转换数据为统一格式
                    return data.data.map(track => ({
                        id: track.id,
                        title: track.title,
                        artist: track.user.name,
                        duration: Math.floor(track.duration),
                        cover: track.artwork ? track.artwork["480x480"] : "https://source.unsplash.com/random/300x300/?music",
                        url: `${endpoint}${track.stream_url}`,
                        isLocal: false
                    }));
                } catch (error) {
                    console.warn(`API端点 ${endpoint} 失败:`, error);
                }
            }
            
            throw new Error("所有API端点均不可用");
        }
        
        // 显示搜索结果
        function displaySearchResults(results) {
            if (!results || results.length === 0) {
                resultsContainer.innerHTML = '<div class="empty-state"><i class="fas fa-search"></i><p>未找到相关歌曲</p></div>';
                document.getElementById('resultsCount').textContent = '0 首歌曲';
                return;
            }
            
            let html = '';
            results.forEach(song => {
                html += `
                    <div class="result-item" data-id="${song.id}">
                        <div class="result-art">
                            ${song.cover ? 
                                `<img src="${song.cover}" alt="${song.title}">` : 
                                `<i class="fas fa-music"></i>`
                            }
                        </div>
                        <div class="result-details">
                            <div class="result-title">${song.title}</div>
                            <div class="result-artist">${song.artist}</div>
                        </div>
                        <div class="song-duration">${formatTime(song.duration)}</div>
                    </div>
                `;
            });
            
            resultsContainer.innerHTML = html;
            document.getElementById('resultsCount').textContent = `${results.length} 首歌曲`;
            
            // 添加搜索结果点击事件
            document.querySelectorAll('.result-item').forEach(item => {
                item.addEventListener('click', () => {
                    const songId = item.dataset.id;
                    const song = results.find(s => s.id === songId);
                    
                    if (song) {
                        // 添加到播放列表
                        song.isLocal = false;
                        addToPlaylist(song);
                        
                        // 显示通知
                        showNotification(`已添加: ${song.title}`);
                        
                        // 更新歌单计数
                        updatePlaylistCount();
                    }
                });
            });
        }
        
        // 显示通知
        function showNotification(message) {
            notification.textContent = message;
            notification.classList.add('show');
            
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }
        
        // 页面加载完成后初始化播放器
        window.addEventListener('DOMContentLoaded', initPlayer);
    </script>
</body>
</html>